package com.xiaotao.service.impl;

import com.xiaotao.entity.User;
import com.xiaotao.mapper.UserMapper;
import com.xiaotao.service.UserService;
import com.xiaotao.util.ResponseEnum;
import com.xiaotao.util.ResponseUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public ResponseUtil queryAll() {
        List<User> users = userMapper.queryAll();
        return users != null ? ResponseUtil.get(ResponseEnum.OK, users)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }

    @Override
    public ResponseUtil queryById(Integer id) {
        User user = userMapper.queryById(id);
        return user != null ? ResponseUtil.get(ResponseEnum.OK, user)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }

    @Override
    public ResponseUtil add(User user) {
        Integer add = userMapper.add(user);
        return add > 0 ? ResponseUtil.get(ResponseEnum.OK)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }

    @Override
    public ResponseUtil update(User user) {
        Integer update = userMapper.update(user);
        return update > 0 ? ResponseUtil.get(ResponseEnum.OK)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }

    @Override
    public ResponseUtil delete(Integer id) {
        Integer delete = userMapper.delete(id);
        return delete > 0 ? ResponseUtil.get(ResponseEnum.OK)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }

    @Override
    public ResponseUtil registered(User user) {
        if (user.getUsername() == null || user.getUsername() == "" || user.getPassword() == "" || user.getPassword() == null || user.getPhone() == "" || user.getPhone() == null) {
            return ResponseUtil.getError(400, "账号、密码或手机号不能为空");
        }
        User user1 = userMapper.queryByUsername(user.getUsername());
        if (user1 != null) {
            return ResponseUtil.getError(400, "账号已存在");
        }
        Integer add = userMapper.add(user);
        //后面加激活码缓存
        return add > 0 ? ResponseUtil.get(ResponseEnum.OK)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }

    @Override
    public ResponseUtil login(User user) {
        if (user.getUsername() == null || user.getUsername() == "" || user.getPassword() == "" || user.getPassword() == null) {
            return ResponseUtil.getError(400, "账号或密码不能为空");
        }
        User user1 = userMapper.queryByUsername(user.getUsername());
        if (user1 == null) {
            return ResponseUtil.getError(400, "账号不存在");
        } else if (!user.getPassword().equals(user1.getPassword())) {
            return ResponseUtil.getError(400, "密码错误");
        } else {
            return ResponseUtil.get(ResponseEnum.OK);
        }
    }

}
